<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="训练任务名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入训练任务名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="关联的模型ID" prop="modelId">
        <el-input v-model="queryParams.modelId" placeholder="请输入关联的模型ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['task:task:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['task:task:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['task:task:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" @click="handleExport"
          v-hasPermi="['task:task:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="训练任务ID" align="center" prop="id" width="100" />
      <el-table-column label="训练任务名称" align="center" prop="name" width="180" />
      <el-table-column label="关联的模型" align="center" prop="modelId" width="180">
        <template slot-scope="scope">
          {{ getModelName(scope.row.modelId) }}
        </template>
      </el-table-column>
      <el-table-column label="训练参数" align="center" prop="trainParams" :show-overflow-tooltip="true" />
      <el-table-column label="训练状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="错误信息" align="center" prop="errorMsg" :show-overflow-tooltip="true" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-video-play" @click="handleStartTraining(scope.row)"
            v-if="scope.row.status === 'pending'">开始训练</el-button>
          <el-button size="mini" type="text" icon="el-icon-video-pause" @click="handleStopTraining(scope.row)"
            v-if="scope.row.status === 'running'">停止训练</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleDownload(scope.row)"
            v-if="scope.row.status === 'completed'">下载</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['task:task:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['task:task:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改模型训练任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="训练任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入训练任务名称" />
        </el-form-item>
        <el-form-item label="关联的模型" prop="modelId">
          <el-select v-model="form.modelId" placeholder="请选择关联模型" clearable>
            <el-option v-for="item in modelOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="训练数据文件" prop="trainFile">
          <file-upload v-model="form.trainFile" :limit="1" :fileSize="500" :isImage="false" :fileType="['zip']" />
        </el-form-item>
        <el-form-item label="训练参数(JSON格式)" prop="trainParams">
          <el-input v-model="form.trainParams" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="训练结果文件" prop="resultFile">
          <file-upload v-model="form.resultFile" :limit="1" :fileSize="500" :isImage="false" :fileType="['zip']" />
        </el-form-item>
        <el-form-item label="错误信息" prop="errorMsg">
          <el-input v-model="form.errorMsg" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">模型信息</el-divider>
        <el-table :data="[selectedModel]" v-if="selectedModel.id">
          <el-table-column label="模型名称" prop="name" align="center" />
          <el-table-column label="模型文件" prop="modelFile" align="center" />
          <el-table-column label="源模型ID" prop="sId" align="center" />
        </el-table>
        <el-empty v-else description="请选择关联模型" />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, startTraining, stopTraining, downloadResult } from "@/api/task/task";
import { listModel } from "@/api/model/model";

export default {
  name: "Task",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 模型训练任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 模型选项
      modelOptions: [],
      // 选中的模型
      selectedModel: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        modelId: null,
        trainFile: null,
        trainParams: null,
        status: null,
        resultFile: null,
        errorMsg: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "训练任务名称不能为空", trigger: "blur" }
        ],
        modelId: [
          { required: true, message: "关联的模型ID不能为空", trigger: "blur" }
        ],
        trainFile: [
          { required: true, message: "训练数据文件不能为空", trigger: "blur" }
        ],
      },
      // 状态映射
      statusMap: {
        pending: { type: 'info', text: '待训练' },
        running: { type: 'warning', text: '训练中' },
        completed: { type: 'success', text: '已完成' },
        failed: { type: 'danger', text: '训练失败' }
      },
      // 模型名称缓存
      modelNameMap: new Map()
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询模型训练任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        modelId: null,
        trainFile: null,
        trainParams: null,
        status: null,
        startTime: null,
        endTime: null,
        resultFile: null,
        errorMsg: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.selectedModel = {};
      this.resetForm("taskRef");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryRef");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 获取模型列表 */
    getModelOptions() {
      listModel().then(response => {
        this.modelOptions = response.rows;
        // 更新模型名称缓存
        this.modelOptions.forEach(model => {
          this.modelNameMap.set(model.id, model.name);
        });
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getModelOptions();
      this.open = true;
      this.title = "添加模型训练任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.getModelOptions();
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模型训练任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["taskRef"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除模型训练任务编号为"' + ids + '"的数据项？').then(() => {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('task/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    },
    /** 下载训练结果文件 */
    handleDownload(row) {
      if (row.resultFile) {
        downloadResult(row.id).then(response => {
          // 检查响应类型
          const contentType = response.type;
          if (contentType !== 'application/x-zip-compressed') {
            // 如果不是zip文件，可能是错误信息
            return response.text().then(text => {
              this.$modal.msgError(text || "下载失败");
              throw new Error(text);
            });
          }

          const blob = new Blob([response], { type: 'application/x-zip-compressed' });
          const fileName = `${row.name}_result.zip`;

          if ('download' in document.createElement('a')) {
            const link = document.createElement('a');
            link.download = fileName;
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
          } else {
            navigator.msSaveBlob(blob, fileName);
          }
        }).catch((error) => {
          if (!error.message) {
            this.$modal.msgError("下载失败");
          }
        });
      } else {
        this.$modal.msgError("没有可下载的训练结果文件");
      }
    },
    /** 开始训练 */
    handleStartTraining(row) {
      this.$modal.confirm('确认开始训练任务"' + row.name + '"?').then(() => {
        return startTraining(row.id);
      }).then(() => {
        this.$modal.msgSuccess("已开始训练");
        this.getList(); // 刷新列表
      }).catch(() => { });
    },
    /** 停止训练 */
    handleStopTraining(row) {
      this.$modal.confirm('确认停止训练任务"' + row.name + '"?').then(() => {
        return stopTraining(row.id);
      }).then(() => {
        this.$modal.msgSuccess("已停止训练");
        this.getList(); // 刷新列表
      }).catch(() => { });
    },
    // 获取状态类型
    getStatusType(status) {
      return this.statusMap[status]?.type || '';
    },
    // 获取状态文本
    getStatusText(status) {
      return this.statusMap[status]?.text || status;
    },
    // 获取模型名称
    getModelName(modelId) {
      if (!this.modelNameMap.has(modelId)) {
        const model = this.modelOptions.find(m => m.id === modelId);
        this.modelNameMap.set(modelId, model?.name || modelId);
      }
      return this.modelNameMap.get(modelId);
    }
  },
  watch: {
    'form.modelId': {
      handler(newVal) {
        if (newVal) {
          this.selectedModel = this.modelOptions.find(item => item.id === newVal) || {};
        } else {
          this.selectedModel = {};
        }
      }
    }
  }
};
</script>

<style scoped>
.el-table {
  width: 100%;
  margin-top: 15px;
}

.el-table .el-table__cell {
  padding: 8px 0;
}

.el-tag {
  margin-right: 5px;
}
</style>